#include "log.h"
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#include <QDateTime>
#include <QMessageBox>

CDebugLog::CDebugLog()
{
    filename = NULL;
    filename = (char *)malloc(256);
    memset(filename, 0, 256);
    if(access(LOG_FILE_PATH, F_OK) < 0)
    {
        if(mkdir(LOG_FILE_PATH, 0777 ) < 0 )
            return;
    }
    strcat(filename, LOG_FILE_PATH);
    strcat(filename, LOG_FILE_NAME);
    fp = NULL;
    fp = fopen(filename, "a+");
    if(fp && fseek(fp, 0, SEEK_END)>-1)
    {
        DebugLog("version 2013.4.2.0");
        if(ftell(fp) >= 100*1024*1024)   //文件大于100M时删除此文件
        {
            fclose(fp);
            fp = NULL;
            fp = fopen(filename, "w+");
            DebugLog("The log file is too big, clear it!");
        }
    }
}
CDebugLog::~CDebugLog()
{
    if(fp)
    {
        fclose(fp);
    }
    if(filename)
    {
        free(filename);
    }
}

void CDebugLog::DebugLog(const char *arg, ...)
{
    char buf[512] = {0};

    time_t tm;
    time(&tm);
    struct tm *timeinfo = localtime(&tm);
    strcpy(buf, asctime(timeinfo));
    strcpy(buf + strlen(buf) - 1, " : ");
    if(fp )  //写入日志文件
    {
        fwrite(buf, 1, strlen(buf), fp);
        fflush(fp);
    }

    va_list list;
    va_start(list, arg);
    vsprintf(buf, arg, list);
    va_end(list);

    qDebug("%s", buf);
    strcat(buf, "\n");

    if(fp)  //写入日志文件
    {
        fwrite(buf, 1, strlen(buf), fp);
        fflush(fp);
    }
}













































